#!/usr/bin/env python3
"""
系统状态最终检查
"""

import sys
import os
import sqlite3
from pathlib import Path

def check_system_status():
    """检查系统状态"""
    print("🔍 学术研究自动化系统 - 最终状态检查")
    print("=" * 60)
    
    # 检查核心文件
    print("📁 核心文件检查:")
    core_files = [
        'start.py',
        'data/research.db',
        'templates/index.html',
        'templates/projects.html',
        'static/css/style.css'
    ]
    
    all_files_exist = True
    for file_path in core_files:
        if Path(file_path).exists():
            size = Path(file_path).stat().st_size
            print(f"✅ {file_path} ({size} bytes)")
        else:
            print(f"❌ {file_path} 缺失")
            all_files_exist = False
    
    # 检查数据库
    print(f"\n🗄️ 数据库检查:")
    try:
        conn = sqlite3.connect('data/research.db')
        cursor = conn.cursor()
        
        # 检查表
        tables = ['projects', 'literature', 'research_plans']
        for table in tables:
            cursor.execute(f"SELECT COUNT(*) FROM {table}")
            count = cursor.fetchone()[0]
            print(f"✅ 表 {table}: {count} 条记录")
        
        conn.close()
        db_ok = True
    except Exception as e:
        print(f"❌ 数据库错误: {e}")
        db_ok = False
    
    # 检查启动脚本
    print(f"\n🚀 启动脚本检查:")
    try:
        # 测试导入
        import flask
        print("✅ 依赖包正常")
        
        # 检查start.py语法
        with open('start.py', 'r', encoding='utf-8') as f:
            content = f.read()
            compile(content, 'start.py', 'exec')
        print("✅ start.py 语法正常")
        
        startup_ok = True
    except Exception as e:
        print(f"❌ 启动脚本问题: {e}")
        startup_ok = False
    
    # 检查演示文件
    print(f"\n🎮 演示文件检查:")
    demo_files = [
        'demo_automation.html',
        'demo_chat_interface.html',
        'demo_real_deliverables.html'
    ]
    
    demo_count = 0
    for demo_file in demo_files:
        if Path(demo_file).exists():
            print(f"✅ {demo_file}")
            demo_count += 1
        else:
            print(f"⚠️ {demo_file} 不存在")
    
    # 生成报告
    print("\n" + "=" * 60)
    print("📊 系统状态总结:")
    
    issues = []
    if not all_files_exist:
        issues.append("核心文件缺失")
    if not db_ok:
        issues.append("数据库问题")
    if not startup_ok:
        issues.append("启动脚本问题")
    
    if not issues:
        print("🎉 系统状态完全正常！")
        print("\n🚀 启动方式:")
        print("   python start.py")
        print("\n🌐 访问地址:")
        print("   http://localhost:8080")
        print("\n📖 可用功能:")
        print("   • 项目管理界面")
        print("   • 数据库驱动的项目列表")
        print("   • 系统状态API")
        print(f"   • {demo_count} 个演示页面")
        
        print("\n✨ 问题已完全解决！系统可以正常运行。")
        return True
    else:
        print(f"⚠️ 发现问题: {', '.join(issues)}")
        return False

def main():
    """主函数"""
    success = check_system_status()
    return 0 if success else 1

if __name__ == '__main__':
    exit_code = main()
    sys.exit(exit_code)